package cn.school.tencent.service.impl;


import cn.hutool.core.date.DateTime;
import cn.school.tencent.TencentCosConstantUtils;
import cn.school.tencent.service.TencentCosFileService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @className: TencentCosFileServiceImpl
 * @author: Alex
 * @date: 2023/9/9
 **/
@Service
public class TencentCosFileServiceImpl implements TencentCosFileService {
	
	@Override
	public String uploadImgByPath(String filePath) {
		File file = FileUtils.getFile(filePath);
		return uploadImg(getMultipartFile(file));
	}
	
	private MultipartFile getMultipartFile(File file) {
		FileItem item = new DiskFileItemFactory().createItem("file"
				, MediaType.MULTIPART_FORM_DATA_VALUE
				, true
				, file.getName());
		try (InputStream input = new FileInputStream(file);
			 OutputStream os = item.getOutputStream()) {
			// 流转移
			IOUtils.copy(input, os);
		} catch (Exception e) {
			throw new IllegalArgumentException("Invalid file: " + e, e);
		}
		
		return new CommonsMultipartFile(item);
	}
	
	
	@Override
	public String uploadImg(MultipartFile file) {
		String secretId = TencentCosConstantUtils.ACCESS_KEY_ID;
		String secretKey = TencentCosConstantUtils.ACCESS_KEY_SECRET;
		
		COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
		
		Region region = new Region(TencentCosConstantUtils.REGION);
		ClientConfig clientConfig = new ClientConfig(region);
		clientConfig.setHttpProtocol(HttpProtocol.https);
		
		COSClient cosClient = new COSClient(credentials, clientConfig);
		
		String bucketName = TencentCosConstantUtils.BUCKET_NAME;
		
		String key = UUID.randomUUID().toString().replaceAll("-","")
				+file.getOriginalFilename();
		//对上传文件分组，根据当前日期2022/8/15
		String dateTime = new DateTime().toString("yyyy/MM/dd");
		key = dateTime+"/"+key;
		
		try {
			//获取上传文件的输入流
			InputStream inputStream = file.getInputStream();
			
			ObjectMetadata objectMetadata = new ObjectMetadata();
			
			PutObjectRequest putObjectRequest = new PutObjectRequest(
					bucketName,
					key,
					inputStream,
					objectMetadata);
			
			// 高级接口会返回一个异步结果Upload
			PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
			// 上传失败,处理返回路径
			
			//返回上传文件的路径
			String url = "https://"+bucketName+"."+"cos"+"."+TencentCosConstantUtils.REGION+".myqcloud.com"+"/"+key;
			return url;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	
	}
}
